const express=require('express');
const router = express.Router();
const sqlFn=require('./config');
const jwt=require('jsonwebtoken');
const jwtSecret=require('./jwtSecret');
const url=require('url');
const fs=require('fs');
const multer=require('multer');
/* 
登录接口
*/
router.post('/login',(req, res) => {
  const username=req.body.username;
  const password=req.body.password;  
  const sql='select * from user where username=? and password=?';
  const arr=[username,password]
  sqlFn(sql,arr,result=>{
    if(result.length>0){
    const token=jwt.sign({
          id:result[0].id,
          username:result[0].username,
      },jwtSecret.jwtSecret)
      res.send({
        token,
        code:200,
        msg:'认证成功'
      })
    }else{
      res.send({
        msg:'用户名密码错误'
      })
    }
  })
})

/* 
注册接口
*/

router.post('/register',(req,res)=>{
  const username=req.body.username;
  const password=req.body.password;
  const email=req.body.email;
  const sql='insert into user values(null,?,?,?)';
  const arr=[username,password,email];
  sqlFn(sql,arr,result=>{
    if(result.affectedRows>0){
      res.send({
        msg:'用户注册成功'
      })
    }else{
      res.send({
        msg:'注册失败'
      })
    }
  })
})

/* 
产品列表数据
*/
router.get('/backend/item/selectTbItemAllByPage',(req, res)=>{
  //读取参数
  // var page=url.parse(req.url,true).query.page||1;
  const page=req.query.page||1;
  const sql="select * from project order by id desc limit 10 offset "+(page-1)*10
  sqlFn(sql,null,result=>{
    if(result.length>0){
      res.send({
        code:200,
        result,
        msg:'读取数据成功'
      })
    }else{
      res.send({
        msg:'读取数据失败'
      })
    }
  })
})
/* 
商品总页数
*/
router.get('/total',(req, res) => {
  const sql="select count(*) from project where id";
  sqlFn(sql,null,result =>{
    if(result.length>0){
      res.send({
        code:200,
        result,
        msg:'请求成功'
      })
    }else{
      res.send({
        msg:"请求失败"
      })
    }
  })
})
/* 
产品模糊查询
*/
router.get('/search',(req,res)=>{
  // const search=url.parse(req.url,true).query.search;
  const search=req.query.search;
  const sql="select * from project where concat(`title`,`sellPoint`,`descs`) like '%" + search + "%'"
  sqlFn(sql,null,result=>{
    if(result.length>0){
      res.send({
        code:200,
        result,
        msg:'请求成功'
      })
    }else{
      res.send({
        msg:"请求失败"
      })
    }
  })
})
/* 
类目选择
*/
router.get("/backend/itemCategory/selectItemCategoryByParentId",(req,res)=>{
  const id=req.query.id||1;
  const sql="select * from category where id=?"
  const arr=[id];
  sqlFn(sql,arr,result=>{
    if(result.length>0){
      res.send({
        code:200,
        result,
        msg:'请求成功'
      })
    }else{
      res.send({
        msg:"请求失败"
      })
    }
  })
})
/**
 * 上传图片
 */
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
      cb(null, "./upload/")
  },
  filename: function (req, file, cb) {
      cb(null, Date.now() + "-" + file.originalname)
  }
})

var createFolder = function (folder) {
  try {
      fs.accessSync(folder);
  } catch (e) {
      fs.mkdirSync(folder);
  }
}

var uploadFolder = './upload/';
createFolder(uploadFolder);
var upload = multer({ storage: storage });

router.post('/upload', upload.single('file'), function (req, res, next) {
  var file = req.file;
  console.log('文件类型：%s', file.mimetype);
  console.log('原始文件名：%s', file.originalname);
  console.log('文件大小：%s', file.size);
  console.log('文件保存路径：%s', file.path);
  res.json({ res_code: '0', name: file.originalname, url: file.path });
});
/* 
商品添加数据
*/
router.get("/backend/item/insertTbItem", (req, res) => {
  var title = req.query.title || "";
  var cid = req.query.cid || "";
  var sellPoint = req.query.sellPoint || "";
  var price = req.query.price || "";
  var num = req.query.num || "";
  var desc = req.query.desc || "";
  var image = req.query.image || "";
  const sql = "insert into project values (null,?,?,?,?,?,?,'',1,'','',?)";
  var arr = [title, image, sellPoint, price, cid, num, desc];
  sqlFn(sql, arr, result => {
      if (result.affectedRows > 0) {
          res.send({
              code: 200,
              msg: "添加成功"
          })
      } else {
          res.send({
              code: 500,
              msg: "添加失败"
          })
      }
  })
})
/* 
产品删除
*/
router.get('/backend/item/deleteItemById',(req, res)=>{
  var id=req.query.id;
  var sql ="delete from project where id=?";
  var arr=[id];
  sqlFn(sql,arr,result=>{
    if (result.affectedRows > 0) {
      res.send({
          code: 200,
          msg: "删除成功"
      })
  } else {
      res.send({
          code: 500,
          msg: "删除失败"
      })
  }
  })
})
/* 
预更新
*/
router.get("/backend/item/preUpdateItem",(req,res)=>{
  var id=req.query.id;
  const sql="select * from project where id=?";
  sqlFn(sql,[id],result=>{
    if(result.length>0){
      res.send({
        status:200,
        result
      })
    }else{
      res.send({
        status:500,
        msg:"预更新失败"
      })
    }
  })
})
/* 
修改接口
*/
router.get("/backend/item/updateTbItem",(req,res)=>{
  var id = req.query.id;
    var title = req.query.title || "";
    var sellPoint = req.query.sellPoint || "";
    var price = req.query.price || "";
    var num = req.query.num || "";
    var desc = req.query.desc || "";
    var image = req.query.image || "";
    var cid = req.query.cid;
    var sql = "update project set title=?,sellPoint=?,cid=?,price=?,num=?,descs=?,image=? where id=?";
    var arr = [title, sellPoint, cid, price, num, desc, image, id];
    sqlFn(sql, arr, result => {
        if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "修改成功"
            })
        } else {
            res.send({
                status: 500,
                msg: "修改失败"
            })
        }
    })
})
/* 
规格参数
*/
router.get("/backend/itemParam/selectItemParamAll",(req, res)=>{
  const page=req.query.page||1;
  const sql="select * from params order by id desc limit 10 offset "+(page-1)*10;
  sqlFn(sql,null,result=>{
    if(result.length>0){
      res.send({
        status:200,
        result
      })
    }else{
      res.send({
        status:500,
        msg:"查询失败"
      })
    }
  })
})
/* 
添加规格参数
*/
router.get("/backend/itemParam/insertItemParam",(req,res)=>{
  var itemCatId=req.query.itemCatId;
  var paramsContent=req.query.content;
  var sql="insert into params values (null,?,?)";
  sqlFn(sql,[itemCatId,paramsContent],result=>{
    if (result.affectedRows > 0) {
      res.send({
          status: 200,
          msg: "修改成功"
      })
  } else {
      res.send({
          status: 500,
          msg: "修改失败"
      })
  }
  });
})
/* 
删除规格参数
*/
router.get("/params/delete", (req, res) => {
  var id = req.query.id;
  const sql = "delete from params where id=?"
  sqlFn(sql, [id], result => {
      if (result.affectedRows > 0) {
          res.send({
              status: 200,
              msg: "删除成功"
          })
      } else {
          res.send({
              status: 500,
              msg: "删除失败"
          })
      }
  })
})
/**
 * 查询规格参数-商品管理
 */
router.get("/product/params/paramsItem", (req, res) => {
  var cid = req.query.cid;
  var sql = "select * from params where itemCatId=?"
  sqlFn(sql, [cid], result => {
      if (result.length > 0) {
          res.send({
              status: 200,
              result
          })
      } else {
          res.send({
              status: 500,
              msg: "无更多数据"
          })
      }
  })
})


module.exports =router